package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApFollowBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.dto.FollowBehaviorDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP关注行为表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-03-29
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements IApFollowBehaviorService {

    @Autowired
    private IApBehaviorEntryService behaviorEntryService;


    /**
     * 将关注行为操作入库
     *
     * @param dto 关注行为信息
     */
    @Override
    public void saveFollowBehavior(FollowBehaviorDto dto) {
        //1.保存用户关注行为记录
        //1.1 根据用户ID或者设备ID 查询行为实体对象
        ApBehaviorEntry entry = behaviorEntryService.getEntry(dto.getUserId(), dto.getEquipmentId());

        //1.2 构建关注行为实体对象 执行保存或者更新
        ApFollowBehavior followBehavior = new ApFollowBehavior();
        followBehavior.setEntryId(entry.getId());
        followBehavior.setFollowId(dto.getFollowId());
        followBehavior.setOperation(dto.getOperation());

        //1.2.1 用户没有关注作者 执行保存
        LambdaQueryWrapper<ApFollowBehavior> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApFollowBehavior::getEntryId, entry.getId());
        queryWrapper.eq(ApFollowBehavior::getFollowId, dto.getFollowId());
        ApFollowBehavior one = this.getOne(queryWrapper);
        if (one == null) {
            this.save(followBehavior);
        } else {
            //1.2.2 用户已经存在关注记录 提交操作行为 跟 数据库中是否一致 不一致：更新
            if (!one.getOperation().equals(dto.getOperation())) {
                one.setOperation(dto.getOperation());
                this.updateById(one);
            }
        }


    }
}
